<template>
	<view class="flex-col page min-vh-100" style="background-color: #F3F3F3;">
		<view class="flex-col">
			<!-- <CustomSwiper :list="promotionBannerList" height="440" mode="rect" border-radius="4"></CustomSwiper> -->
			<view class="position-relative">
				<u-swiper class="swipes" :list="promotionBannerList" height="440" border-radius="0"></u-swiper>
				<view class="">
					<view class="d-flex  align-items-center py-2 hot  px-3">
						<image class="img-32" src="../../static/imgs/hot.png" mode=""></image>
						<text class="font-500 ps-1 font-12 text-white flex-1">{{room.promotion_rent_info||'-'}}</text>
					</view>
				</view>
			</view>
			<view class="flex-col card px-3 ">
				<view class="brs-12 bg-white overflow-hidden py-3">
					<view class="flex-row  w-100" style="flex-wrap: nowrap; justify-content: flex-start;">
						<view class="left-section"></view>
						<view class="font-600 font-20 text-222426 px-3"
							style="word-wrap: break-word; flex-grow: 1;flex-shrink: 1;">
							{{room.room_name||'-'}}-{{room.store_name||'-'}}
						</view>
					</view>
					<!-- <view class="d-flex  pt-3  flex-wrap w-100 px-1">
						<view class="u-text-center w-20 pb-2" v-for="v,i in room.features" :key="i">
							<image class="img-88 round" :src="v.icon_url" mode=""></image>
							<view class="text-AAB5BF font-12 font-500 pt-1">{{v.title}}</view>
						</view>
					</view> -->
					<view class="d-flex align-items-center pt-3">
						<scroll-view class="scroll_container ps-2" scroll-x="true" @touchmove.stop>
							<view class="k_item" @click="switchDate(item,index)" v-for="(item, index) in dateList"
								:key="index">
								<view
									class="d-flex flex-column align-items-center font-12 font-500 pt-1   scroll-content"
									:class="idx==index?'active text-theme':'text-AAB5BF'">
									<text class="">{{moment(item.date).format('MM-DD')}}</text>
									<text>周{{item.week}}</text>
								</view>
							</view>
						</scroll-view>
						<view class="canlader flex-1 " @click="showCalender=true">
							<view class="d-flex flex-column align-items-center  font-12 font-500 pt-2 "
								:class="idx==-1?'active canlader-pic':'justify-content-center'" style="height: 116rpx;">
								<template v-if="idx==-1">
									<text class="text-theme ">{{cal_text.title}}</text>
									<text class="text-theme">周{{cal_text.week}}</text>
								</template>
								<image v-else class="img-48" src="../../static/imgs/calendar.png" mode=""></image>
							</view>
						</view>
					</view>
					<view class="row mx-2 mt-3 pt-1">
						<view class="col-4 px-2 mb-12" v-for="v,i in timepills" :key="i" @click="choosepill(v,i)">
							<view class=" brs-4 font-600 pt-1  overflow-hidden d-flex flex-column"
								:class="v.state?v.state==2?'bg-gray':'bg-yellow':'bg-blue'">
								<view class="text-white  font-11  px-2 pb-1 d-flex justify-content-between">
									<text>{{v.noon}}</text>
									<text>{{v.price}}元</text>
								</view>
								<view
									class="text-222426   bg-white px-2 pt-2 pb-1 font-12  u-text-center d-flex justify-content-between align-items-center"
									:class="v.state==1?'choose':''">
									<text>{{v.start}} </text>- <text>{{handleTime(v.end)}}</text>
								</view>
							</view>
						</view>
						<view v-if="!timepills.length" class="empty d-flex justify-content-center flex-column align-items-center ">
							<image src="../../static/imgs/emptyN.png" class="img"
								style="width: 225rpx;height: 238rpx;" />
							<view class="des ">今天教室无时间段开放</view>
						</view>
					</view>
					<view class="px-3 d-flex pt-3 mt-1 flex-col" style="line-height: 40rpx;">
						<view class="d-flex items-center">
							<image class="img-36" src="../../static/imgs/warning.png" mode=""></image>
							<text class="font-600 font-14 text-222426 ps-2">注意事项</text>
						</view>
						<!-- 租用开始前{{rent_refund}}小时 -->
						<text
							class="text-666D73  flex-1 font-12 font-500">1.{{rent_at_least_min}}分钟起订，灰色为已被预订，可以在“我的预订”自助退订。<text
								style="color: #D85886;"
								@click="$u.route({url:'pages/myReservation/ruleDescription'})">退订规则说明</text> </text>
						<text
							class="text-666D73  flex-1 font-12 font-500">2.支持继订，如果前面是您你订单，我们支持继订</text>
						<text
							class="text-666D73  flex-1 font-12 font-500">3.如有任何问题请联系客服微信号rabbitanddream</text>
					</view>
				</view>

			</view>
			<view v-show="room.wifi_name||room.bluetooth_audio_name" class="flex-col mx-3 mt-3 bg-white brs-12">
				<view class="flex-row  w-100 "
					style="flex-wrap: nowrap; justify-content: flex-start;margin-top: 24rpx;">
					<view class="left-section"></view>
					<view class="px-3"
						style="word-wrap: break-word; flex-grow: 1;flex-shrink: 1;font-weight: 500;font-size: 32rpx;line-height: 48rpx;">
						房间说明
					</view>
				</view>
				<view class="flex-col list " style="margin-bottom: 24rpx;">
					<view class="row mx-3 mt-12">
						<view class="col-6 ps-0 pe-2 position-relative" v-show="room.wifi_name" @click="showWifi=true">
							<view class="bg-F2F6FC ps-12 pt-12 pb-3 brs-8">
								<view class="d-flex align-items-center">
									<image class="img-36" src="../../static/imgs/wifi.png" mode=""></image>
									<text class="text-222426 font-14 font-600 ps-1">WIFI</text>
								</view>
								<!-- 			<view class="font-11 font-500 text-AAB5BF ps-36 pt-1">
									名字：<text class=" text-222426 font-600">{{room.wifi_name}}</text>
								</view>
								<view class="font-11 font-500 text-AAB5BF ps-36 pt-1">
									密码：<text class=" text-222426 font-600">{{room.wifi_pwd}}</text>
								</view> -->
								<view class="one_key_connet_wifi">一键Wifi</view>
							</view>
							<image class="bg-wifi" src="../../static/imgs/wifi-bg.png" mode=""></image>
						</view>
						<view class="col-6 pe-0 ps-2 position-relative" v-show="room.bluetooth_audio_name">
							<view class="bg-F2F6FC ps-12 pt-12 pb-3 brs-8">
								<view class="d-flex align-items-center">
									<image class="img-36" src="../../static/imgs/lanya.png" mode=""></image>
									<text class="text-222426 font-14 font-600 ps-1">蓝牙音响</text>
								</view>
								<view class="font-11 font-500 text-AAB5BF ps-36 pt-1">
									<text class=" text-222426 font-600">{{room.bluetooth_audio_name}}</text>
								</view>
								<view class="font-11 font-500 text-AAB5BF ps-36 pt-1">
									手机/电脑可直接连接
								</view>
							</view>
							<image class="bg-wifi" src="../../static/imgs/lanya-bg.png" mode=""></image>
						</view>
					</view>
				</view>
			</view>
			<view class="flex-col mx-3 bg-white brs-12 mt-3">
				<view class="flex-row  w-100 "
					style="flex-wrap: nowrap; justify-content: flex-start;margin-top: 24rpx;">
					<view class="left-section"></view>
					<view class="px-3"
						style="word-wrap: break-word; flex-grow: 1;flex-shrink: 1;font-weight: 500;font-size: 32rpx;line-height: 48rpx;">
						温馨提示
					</view>
				</view>
				<view class="mb-5 warning bg-white brs-12 text-222426 font-14 font-500 px-3 d-flex flex-column">
					<view v-html="room.room_descriptioncontent"></view>
				</view>
			</view>
		</view>
		<view class="go position-fixd bg-white w-100">
			<view class="d-flex justify-content-end align-items-center">
				<view class="text-theme pe-12 d-flex flex-column align-items-end">
					<view class="">共计：<text class="font-28 font-bold">{{price}}</text><text
							style="padding-left: 6rpx;">元</text> </view>
					<view v-if="vuex_has_login" class="font-12 text-666D73 font-500">使用优惠券后<text
							class="text-EE2D21 ">{{diffPrice}}元</text>
					</view>
				</view>
				<view class="btns" @click="goPayment">
					<button class="btn bg-theme" :disabled="!price">下一步</button>
				</view>
			</view>
		</view>
		<u-calendar v-model="showCalender" mode="date" active-bg-color="#D85886" :min-date="rent_calendar_min_date"
			:max-date="rent_calendar_max_date" @change="calenderChange" :change-year="false"
			:min-year="min_year"></u-calendar>

		<popUp :show="loginShow" @close="close" @registeredSuccess="registeredSuccess" />

		<!-- wifi弹框 -->
		<u-modal @cancel="copyWord(room.wifi_pwd)" confirm-color="#D85886" :mask-close-able="true" title="Wifi信息"
			:async-close="true" confirm-text="一键连接" cancel-text="复制密码" v-model="showWifi" ref="uModal"
			:show-cancel-button="true" @close="showWifi=!showWifi" @confirm="connectWifi">
			<view class="modal-content">
				<view>
					<view class="pop-up-user">
						wifi帐号：{{room.wifi_name}}
					</view>
					<view class="pop-up-user">
						wifi密码：{{room.wifi_pwd}}
					</view>
				</view>
			</view>

		</u-modal>
	</view>
</template>

<script>
	import moment from 'moment'
	export default {
		data() {
			return {
				moment: moment,
				promotionBannerList: [],
				tags: [],
				room: {
					store: {} // 防止还没有加载store的属性就访问，会报错
				},
				rent_calendar_min_date: '',
				rent_calendar_max_date: '',
				has_calender: 0,
				selectdate: moment(new Date()).format('YYYY-MM-DD'),
				dateList: [],
				rent_at_least_min: 60,
				rent_refund: 0,
				timepills: [],
				displaytimepills: [],
				selecttimepills: [], //选择的时间段
				price: 0,
				diffPrice: 0,
				showCalender: false,
				cal_text: {
					date: '',
					week: ''
				},
				idx: 0,
				couponList: [],
				loginShow: false,
				showWifi: false,
			};
		},
		computed: {
			min_year: function() {
				let date = new Date();
				return date.getFullYear()
			}
		},
		onLoad(options) {
			let room_id = options.id
			this.loadAndRefresh(room_id)
			if (this.vuex_has_login) {

				this.getUserCoupon()
			}
		},
		onShow() {
			if (this.vuex_reserve_info.reserve_id) {
				console.log(this.vuex_reserve_info.reserve_id);
				let reserve_id = this.vuex_reserve_info.reserve_id
				this.$u.api.deleteReservationApi({
					id: reserve_id
				}).then((res) => {

				})
				this.$u.vuex('vuex_reserve_info', {}) // 删除后置空, 不等待网路返回
			}
		},

		onPullDownRefresh() {
			this.loadAndRefresh(this.room.id)
			setTimeout(uni.stopPullDownRefresh(), 1500)
		},
		watch: {
			vuex_token(news, odd) {
				if (news) {
					this.getInfo()
				}
			}
		},
		methods: {
			handleTime(str) {
				if (str.includes('29')) {
					return str.replace(29, 30)
				}
				if (str.includes('59')) {
					return str.replace(/(\d{1,2}):(\d{2})/, (match, hour, minute) => {
						hour = parseInt(hour, 10);
						minute = parseInt(minute, 10);
						if (minute === 59 || (hour === 23 && minute === 59)) {
							hour = (hour + 1) % 24;
							minute = 0;
						}
						return this.pad(hour, 2) + ':' + this.pad(minute, 2);
					});
				}
				return str
			},
			pad(num, size) {
				let s = num + "";
				while (s.length < size) s = "0" + s;
				return s;
			},
			getUserCoupon() {
				this.$u.api.getUserUnusedCoupon().then((res) => {
					this.couponList = res.data
				})
			},
			calenderChange(e) {
				console.log(e);
				if (e.isToday) {
					return
				}
				this.idx = -1
				this.cal_text.title = moment(e.result).format('MM-DD')
				this.cal_text.week = ['日', '一', '二', '三', '四', '五', '六'][moment(moment(e.result).format('YYYY/MM/DD'))
					.day()
				]
				this.selectdate = e.result
				this.$u.api.getRentTimePill({
					roomid: this.room.id,
					date: e.result
				}).then((res) => {
					this.timepills = []
					this.timepills = res.data.map((e, i) => ({
						...e,
						index: i
					}))
					this.price = 0
				})

			},
			loadAndRefresh(room_id) {
				this.$u.api.getRoomPage({
						id: room_id
					})
					.then((res) => {
						if (1 == res.code) {
							this.room = res.data
							this.promotionBannerList = res.data.room_slideimages
						}
					})
				this.$u.api.reserveInit({
					roomid: room_id
				}).then((res) => {
					// if (1 == res.code) {
					for (let i = 0; i < res.data.rent_reserve_advance_day; i++) {
						this.dateList.push({
							date: moment(moment(new Date()).add(i,
								'days')).format('YYYY-MM-DD'),
							week: ['日', '一', '二', '三', '四', '五', '六'][moment(moment(moment(new Date()).add(
								i,
								'days')).format('YYYY/MM/DD')).day()]
						})
					}
					this.rent_at_least_min = res.data.rent_at_least_min ? res.data.rent_at_least_min : 60
					this.rent_refund = res.data.rent_refund ? res.data.rent_refund : 0
					this.timepills = res.data.rent_time_pills.map((e, i) => ({
						...e,
						index: i
					}))
					this.timepills = this.filterTime(this.timepills)

					this.rent_calendar_max_date = moment(moment(new Date()).add(+res.data
						.rent_reserve_advance_day - 1,
						'days')).format('YYYY-MM-DD');
					this.rent_calendar_min_date = moment(new Date()).format('YYYY-MM-DD')
					this.has_calender = res.data.has_calender
					// }
				})
			},

			filterTime(arr) {
				const now = moment();
				const filteredData = arr.filter(item => {
					const startTime = moment(item.start, 'HH:mm');
					const endTime = moment(item.end, 'HH:mm');
					return now.isBetween(startTime, endTime) || now.isBefore(endTime);
				});
				return filteredData
			},

			switchDate({
				date
			}, index) {
				if (this.idx == index) return
				this.idx = index
				this.selectdate = date
				this.$u.api.getRentTimePill({
					roomid: this.room.id,
					date: date
				}).then((res) => {
					this.timepills = []
					this.timepills = res.data.map((e, i) => ({
						...e,
						index: i
					}))
					if (!index) {
						this.timepills = this.filterTime(this.timepills)
					}
					this.price = 0
				})
			},
			choosepill(v, i) {
				if (v.state == 2) return
				this.timepills[i].state = v.state ? 0 : 1
				if (this.timepills.length) {
					this.price = this.timepills.filter((e) => e.state == 1).reduce((a, b) => parseInt(a) + parseInt(
						b.price), 0)
					if (!this.couponList.length) {
						this.diffPrice = this.price
					} else {
						this.diffPrice = this.price - Math.max(...this.couponList.map((e) => {
							if (e.min_price) {
								if (this.price >= e.min_price) {
									return e.price
								} else {
									return 0
								}
							}
							return e.price
						}))
					}
					if (this.diffPrice < 0) {
						this.diffPrice = 0
					}
				} else {
					this.price = 0
				}
			},

			goPayment() {

				if (this.isLess(this.timepills.filter(e => e.state == 1), this.rent_at_least_min)) {
					return this.$u.toast('请选择时间，最少' + this.rent_at_least_min + '分钟起订哦~', 2000);
				}
				let arr = []
				arr = this.timepills.filter(e => e.state == 1).map(a => a.index)
				arr.sort((a, b) => a -
					b); // 使用sort()方法对数组进行排序

				for (let i = 0; i < arr.length - 1; i++) {
					if (arr[i] + 1 !== arr[i + 1]) { // 检查相邻的两个数字是否连续
						return this.$u.toast('请选择连续时间段', 2000);
					}
				}

				if (!this.vuex_has_login) return this.isShowLogin()
				if (this.vuex_has_login && !Number(this.vuex_user.is_realname)) return this.$u.route({
					url: 'pages/myCenter/auth'
				});

				this.$u.vuex('vuex_reserve_info', {
					room_id: this.room.id,
					selectdate: this.selectdate,
					timepills: this.timepills.filter(e => e.state == 1),
				})

				if (!this.vuex_has_login) {
					// await this.wx_login()
					setTimeout(() => {
						this.$u.route({
							url: 'pages/index/payment'
						});
					}, 100)
				} else {
					this.$u.route({
						url: 'pages/index/payment'
					});
				}
				
			},

			isLess(arr, time) {
				let totalDuration = 0
				// for (let timeStr of arr) {
				// 	const [start, end] = [timeStr.start, timeStr.end].map(t => moment(`${this.selectdate} ${t.trim()}`));
				// 	const duration = moment.duration(end.diff(start)).asMinutes();
				// 	totalDuration += duration;
				// }


				// if (arr.find(e => e.end.includes(59) || e.end.includes(29))) {
				// 	return totalDuration < time - 1
				// }
				for (let timeStr of arr) {
					totalDuration += timeStr.duration
				}
				return totalDuration < time

			},
			getInfo() {
				if (this.vuex_has_login) {
					this.$u.api.getUserInfo().then(res => {
						this.$u.vuex('vuex_user', {
							...this.vuex_user,
							...res.data
						})
					})
				}
			},
			// 先尝试直接登录
			isShowLogin() {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						this.$u.api.userLoginApi({
							code: res.code
						}).then(res => {
							if (res.code == 1) {
								this.vuex_login(res)
								this.goPayment()
							} else {
								this.loginShow = true
							}
						})
					},
					fail: (err) => {
						console.log(err);
					},
				})

			},
			registeredSuccess() {
				this.goPayment()
			},
			close() {
				this.loginShow = false
			},

			copyWord(word) {
				uni.setClipboardData({
					data: word,
				})
				uni.showToast({
					title: '复制成功',
					icon: 'success'
				})
				this.showWifi = false
			},

			connectWifi() {

				wx.startWifi({
					success: (e) => {
						wx.connectWifi({
							SSID: this.room.wifi_name, // 替换为您要连接的WiFi的SSID
							password: this.room.wifi_pwd, // 替换为您要连接的WiFi的密码
							success: (res) => {
								console.log('连接WiFi成功', res);
								// 连接成功后的操作，可以在这里执行其他逻辑
								this.$u.toast('连接WiFi成功')

								this.showWifi = false // modal 关闭
							},
							fail: (err) => {
								console.log('连接WiFi失败', err);
								if ('12005' == err.errCode) {
									this.$u.toast("手机wifi连接功能没有打开")
								} else {
									this.$u.toast("连接WiFi失败， 请复制密码手动连接")
								}


								this.showWifi = false // modal 关闭

							}
						});
					},
					fail: (err) => {
						console.log('启动WiFi失败', err);
						this.$u.toast(err.errMsg)

					},
					complete: () => {

					}
				});
			},

		}
	};
</script>

<style scoped lang="scss">
	.left-section {
		margin: 6rpx 0;
		background-color: rgb(216, 88, 134);
		width: 12rpx;
		height: 40rpx;
	}

	::deep .u-indicator-item-round-active {
		background-color: #D85886 !important;
	}

	.swipes {
		::deep .u-swiper-indicator {
			bottom: 50rpx !important;
		}
	}

	.one_key_connet_wifi {
		padding: 18rpx 0;
		margin-left: 44rpx;
		font-weight: bold;
	}

	.modal-content {
		// padding: 40rpx 60rpx;
		height: 220rpx;
		flex: auto;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;


		.pop-up-user {
			font-size: 28rpx;
			font-weight: 400;
			color: #606266;
			margin-bottom: 20rpx;
		}

		// .pop-up-word {
		// 	margin-top: 20rpx;
		// 	width: 100%;
		// 	// font-size: 28rpx;
		// 	// font-weight: 400;
		// 	// color: #606266;
		// }
	}





	.page {
		.hot {
			position: absolute;
			right: 32rpx;
			top: 24rpx;
			background: rgba(0, 0, 0, 0.35);
			border-radius: 84rpx 84rpx 84rpx 84rpx;
		}

		.img-32 {
			width: 32rpx;
			height: 32rpx;
		}

		.card {
			margin-top: -32rpx;
			position: relative;
			z-index: 5;

			.photo {
				width: 100%;
				height: 308rpx;
			}

			.img-36 {
				width: 36rpx;
				height: 36rpx;
			}

			.img-48 {
				width: 48rpx;
				height: 48rpx;
			}

			.border-left {
				border-left: 1rpx solid #F5F7F8;
			}

			.img-88 {
				width: 88rpx;
				height: 88rpx;
			}

			.scrolls {}

			.scroll_container {
				background-color: #ffffff;
				width: calc(100% - 144rpx);
				white-space: nowrap;

				.k_item {
					width: 100rpx;
					// height: 96rpx;
					line-height: 36rpx;
					display: inline-block;

					.scroll-content {
						margin-top: 20rpx;
						margin-bottom: 20rpx;
					}
				}
			}

			.canlader {
				background-color: #ffffff;
				// height: 96rpx;
				// line-height: 36rpx;
				box-shadow: 0px 0px 24px rgba(247, 220, 233, 0.5);
			}

			.canlader-pic {
				line-height: 36rpx;
			}

			// .active {
			// 	border-radius: 12rpx;
			// 	background: linear-gradient(180deg, rgba(24, 40, 219, 0.2) 0%, rgba(24, 40, 219, 0.01) 100%);
			// }
			.active {
				font-size: 30rpx;
			}

		}

		.list {
			.bg-F2F6FC {
				background: #F2F6FC;
			}

			.qd {
				width: 176rpx;
				height: 60rpx;
				line-height: 60rpx;
				text-align: center;
				border-radius: 40rpx 0 40rpx 40rpx;
			}

			.ps-36 {
				padding-left: 36rpx;
			}

			.img-36 {
				width: 36rpx;
				height: 36rpx;
			}

		}

		.warning {
			padding: 36rpx 0 50rpx 0;
			margin-bottom: 40rpx;
		}
	}

	::deep .u-calendar__bottom__btn {
		button {
			background-color: #D85886;
		}

		.u-primary-hover {
			background-color: #D85886 !important;
		}
	}

	.bg-gray {
		background-color: #C4C3C9;
		border: 2rpx solid #C4C3C9;
		position: relative;

		&::before {
			content: '已预定';
			font-weight: 500;
			color: #FFFFFF;
			font-size: 24rpx;
			position: absolute;
			top: 0;
			left: -50rpx;
			padding: 8rpx 0;
			background: #D5809D;
			width: 190rpx;
			text-align: center;
			transform: rotate(-30deg);
		}

	}

	.bg-blue {
		background-color: #D23A71;
		border: 2rpx solid #D23A71;
	}

	.bg-yellow {
		background-color: #4489F0;
		border: 2rpx solid #4489F0;
	}

	.choose {
		background: linear-gradient(-45deg, transparent 16rpx, #fff 0);
	}

	.brs-8-b {
		border-radius: 0 0 16rpx 16rpx;
	}

	.go {
		padding: 16rpx 0 28rpx 0;
		left: 0;
		bottom: 0;
		box-shadow: -2rpx 0rpx 2rpx 0rpx rgba(0, 0, 0, 0.25);
		z-index: 20;

		.btns {
			padding-right: 40rpx;

			.btn {
				width: 240rpx;
				height: 80rpx;
				line-height: 80rpx;
				color: rgb(255, 255, 255);
				font-weight: 600;
				border-radius: 40rpx 0 40rpx 40rpx;

				&[disabled]:not([type]) {
					background-color: #AAB5BF !important;
				}
			}
		}


	}

	.bg-wifi {
		position: absolute;
		right: -20rpx;
		top: -30rpx;
		width: 184rpx;
		height: 184rpx;
		transform: scale(0.9);
	}

	.empty {
		flex: 1;
		margin-bottom: 28rpx;
		margin-top: 60rpx;

		.des {
			font-size: 28rpx;
			color: #909399;
		}
	}
</style>